﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Publishing;

namespace SPGael.CustomFields
{
    class VariationLabelsFieldControl : BaseFieldControl
    {
        private const string RENDERING_TEMPLATE = "VariationLabelsFieldControl";

        protected DropDownList drpVariationLabels;
        protected TextBox txtVariationId;
        protected TextBox txtVariationLabel;

        protected override string DefaultTemplateName
        {
            get { return RENDERING_TEMPLATE; }
        }

        protected override void CreateChildControls()
        {
            if (this.Field == null
                || this.ControlMode == SPControlMode.Display
                || this.ControlMode == SPControlMode.Invalid)
                return;

            base.CreateChildControls();

            // get and check the control in the template
            this.drpVariationLabels = TemplateContainer.FindControl("drpVariationLabels") as DropDownList;
            if (this.drpVariationLabels == null)
                throw new ArgumentException("Dropdown list not found. Please check if your control template is valid.");

            this.txtVariationId = TemplateContainer.FindControl("txtVariationId") as TextBox;
            if (this.txtVariationId == null)
                throw new ArgumentException("VariationId textbox not found. Please check if your control template is valid.");

            this.txtVariationLabel = TemplateContainer.FindControl("txtVariationLabel") as TextBox;
            if (this.txtVariationLabel == null)
                throw new ArgumentException("VariationLabel textbox not found. Please check if your control template is valid.");

            if (!Page.IsPostBack)
            {
                bool useElevatedPrivilege;
                if (!String.IsNullOrEmpty(Convert.ToString(this.Field.GetCustomProperty("useElevatedPrivilege")))
                    && bool.TryParse(this.Field.GetCustomProperty("useElevatedPrivilege").ToString(), out useElevatedPrivilege)
                    && useElevatedPrivilege)
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                              {
                                  PopulateDropDownList();
                              });
                }
                else
                {
                    PopulateDropDownList();
                }
            }
        }

        public override void Focus()
        {
            EnsureChildControls();
            if (this.drpVariationLabels != null)
                drpVariationLabels.Focus();
            else
                base.Focus();
        }

        public override object Value
        {
            get
            {
                EnsureChildControls();
                VariationLabelsFieldValue field = new VariationLabelsFieldValue();
                if (drpVariationLabels != null && drpVariationLabels.SelectedIndex > 0)
                {
                    field.VariationId = this.drpVariationLabels.SelectedItem.Value;
                    field.VariationValue = this.drpVariationLabels.SelectedItem.Text;
                }
                else if (txtVariationId.Text.Length > 0
                    && txtVariationLabel.Text.Length > 0)
                {
                    field.VariationId = this.txtVariationId.Text;
                    field.VariationValue = this.txtVariationLabel.Text;
                }

                return field;
            }
            set
            {
                EnsureChildControls();
                if (!String.IsNullOrEmpty(Convert.ToString(value)))
                {
                    VariationLabelsFieldValue field = new VariationLabelsFieldValue(value.ToString());
                    if (!String.IsNullOrEmpty(field.VariationId))
                    {
                        this.txtVariationId.Text = field.VariationId;
                        this.txtVariationLabel.Text = field.VariationValue;
                        this.drpVariationLabels.Items.FindByValue(field.VariationId).Selected = true;
                    }
                }
            }
        }

        private void PopulateDropDownList()
        {
            using (SPSite spSite = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb spWeb = spSite.RootWeb)
                {
                    string labelsListId = Convert.ToString(spWeb.AllProperties["_VarLabelsListId"]);
                    if (String.IsNullOrEmpty(labelsListId)) throw new NullReferenceException("Cannot retrieve the list id");
                    SPList spListVariationLabels = null;
                    try
                    {
                        spListVariationLabels = spWeb.Lists[new Guid(labelsListId)];
                    }
                    catch { }
                    if (spListVariationLabels == null)
                        throw new NullReferenceException("The variation labels list doesn't exist or you have no privilege to access it");

                    foreach (SPListItem item in spListVariationLabels.Items)
                    {
                        this.drpVariationLabels.Items.Add(new ListItem(Convert.ToString(item["Flag Control Display Name"]), item.Title));
                    }
                }
            }
        }
    }
}
